<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Address;
use app\common\model\GoodsComment;
use app\common\model\GoodsSpecificationSku;
use app\common\model\LogisticCode;
use app\common\model\Order as MyModel;
use app\common\model\OrderGoods;
//use app\order\model\OrderDiscussModel;
//use app\order\model\OrderGoodsModel;
//use app\order\model\OrderModel;
use app\common\model\Refund;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\cache\driver\Redis;
use think\Db;
use think\exception\ValidateException;
use app\common\model\OrderRefund;
class Order extends Api {
    protected $noNeedLogin = [''];//空代表都需要验证
    protected $noNeedRight = ['*'];

    // 需要填写你的 Access Key 和 Secret Key
    protected $accessKey = "V6TAgzCj-JyKcgCS2pfSWwNSsW7QMq6U4Mku5h_Y";
    protected $secretKey = "Ag7hbA-cY1mwwgUvCNmi92bmMBcxk-mI3jsKEGoX";
    protected $bucket = "pinganzhihui";
    /**
     * 订单预览
     */
    public function orderPreview() {
        $userId = $this->auth->id;

        $Cache = new Redis();
        $sku_ids = input('sku_ids', '');
        $address_id = input('address_id', '');
        $userBuyNum = input('userBuyNum/d', 0);
        $buys_type = input('buys_type/d',1);//1是直接下单2是购物车来的
        if (!$buys_type || !$sku_ids) {
            $this->error('参数不完整！');
        }
        if ($sku_ids) {
            $spec_count_map = [];
            $spec_ids = [];

            if ($buys_type == 2) {

                $redis = $Cache->handler();
                $redis_key = 'szshop_cart_' . $userId;
                $goods_info = array_reverse($redis->hkeys($redis_key));
                foreach ($goods_info as $keys => $values) {
                    $g_con = explode('_', $values);
                    $goods_id = $g_con[0];
                    $sku_id = $g_con[1];
                    $sku_arr = explode(',', $sku_ids);
                    $buys_num = $redis->hget($redis_key, $values);
                    foreach ($sku_arr as $ke => $va) {

                        if ($sku_id == $va) {
                            $spec_ids[] = $sku_id;
                            $spec_count_map[$sku_id] = $buys_num;
                            $ret[$keys]['goods_id'] = $goods_id;

                        }
                    }
                }

            } else {
                $spec_ids = $sku_ids;
                if ($userBuyNum <= 0) {
                    $this->error('不可为0');
                }
            }

            $goodsSku = new GoodsSpecificationSku();
            $goodsList = $goodsSku->getGoodsList($spec_ids);
            $goodsList = toArray($goodsList);
            if (empty($goodsList)) {
                $this->success('请求成功!', ['list' => []]);
            }

            // if ($buys_type == 2) {//从购物车里获取

            //     $goods_ids = assoc_unique($ret, 'goods_id');
            //     $goods_ids_arr = array_column($goods_ids, 'goods_id');//二维数组转一维数组
            // } else {
            //     $goods_ids_arr = $goodsList[0]['goods_id'];
            // }
            // $goodsModel = model('app\common\model\Goods');
            // $shop_ids = $goodsModel->whereIn('id', $goods_ids_arr)->select();//查询商家
            // foreach ($shop_ids as $row) {
            //     $row->visible(['id', 'merchant_id']);
            // }
            // $shop_ids = toArray($shop_ids);

            // $shop_ids = assoc_unique($shop_ids, 'merchant_id');

            $all_price = 0;
            $allFreight=0;
            if(!empty($address_id)){
                $addressInfo = Address::get($address_id);
            }else{
                $addressInfo = Address::get(['user_id'=>$userId,'is_default'=>1]);

            }
//            $addressInfo = toArray(\app\common\model\Address::get(['id' => $address_id,'delete_time'=>NULL]));
            if ($addressInfo) {
//                $this->error('');
                $address_id = $addressInfo['id'];
            }
            // foreach ($shop_ids as $k => $v) {
                foreach ($goodsList as $key => &$goods) {
                    if (/*$goods['status']==1||*/$goods['is_del']){
                        $goodsName='商品《'.$goods['goods_name'].'》已下架或删除，请重试';
                        $this->error($goodsName);
                    }
                    $goods['buy_num'] = $buys_type == 1 ? $userBuyNum : $spec_count_map[$goods['id']];
                    if ($goods['buy_num']>$goods['stock']){
                        $this->error('库存不足');
                    }
                    $goods['thumbnail_image'] = get_app_image_url($goods['thumbnail_image']);
                    //   if ($goods['merchant_id'] == $v['merchant_id']) {

                    $goods['all_price'] = bcmul($goods['current_price'],$goods['buy_num'],2);
                    //   $shop_price += $goods['current_price'] * $goods['buy_num'];
                    $all_price += bcmul($goods['current_price'],$goods['buy_num'],2);
                    //运费
//                    if($address_type==1){
//
//                        $Freight= $this->allFreight($goods,$address_id,$userBuyNum);
//                    }else{
//                        $Freight=0;
//                    }
                    $Freight= $this->allFreight($goods,$address_id,$userBuyNum);
                    $allFreight+=$Freight;
                    $goods['Freight'] =$Freight;
                    //  }

                }
                //$argv[$k]['shop_price'] = $shop_price;
            // }
            /**
             * 缓存的一生
             * 设置缓存->
             * 撒子缓存->
             * 复活缓存->
             * 熟悉缓存->
             * 小成缓存->
             * 大成缓存->
             * 删除缓存->
             * 添加缓存->
             * 删库跑路->
             * 清除痕迹->
             * 删除入口->
             * 设置动态->
             * 销声匿迹->
             *  **剧终**
             */

//            $addressInfo = \app\common\model\Address::get(['user_id' => $userId, 'is_default' => 1, 'delete_time' => NULL]);

            $arr['all_price'] = $all_price;
            $arr['total_price'] = $all_price+$allFreight;
            $arr['list'] = $goodsList;
            //查询用户的默认地址
            $arr['addressInfo'] = $addressInfo;
            $arr['allFreight'] = $allFreight;
            $this->success('请求成功!', $arr);
        } else {
            $this->error('请选择商品');
        }
    }

    /**
     * 订单提交
     */
    public function addOrder() {

        $address_id = input('address_id/s');//地址id
        $userId = $this->auth->id;
//        dd($userId);
        $Cache = new Redis();
        $sku_ids = input('sku_ids', '');
        $userBuyNum = input('userBuyNum/d', 0);
        $buys_type = input('buys_type/d');//1是直接下单2是购物车来的
        $address_type = input('address_type/d',1);//1是快递2是自提
        $remarks = input('remarks', '');//备注

        if (!$buys_type || !$sku_ids || empty($address_id)) {
            $this->error('参数不完整！');
        }

        if ($address_type == 1) {
            //查询当前用户收货地址
            $addressInfo = toArray(\app\common\model\Address::get(['id' => $address_id,'delete_time'=>NULL]));
            if (!$addressInfo) {
                $this->error('收货地址不存在');
            }
        }


        if ($sku_ids) {
            $spec_count_map = [];
            $spec_ids = [];

            if ($buys_type == 2) {

                $redis = $Cache->handler();
                $redis_key = 'szshop_cart_' . $userId;
                $goods_info = array_reverse($redis->hkeys($redis_key));
                foreach ($goods_info as $keys => $values) {
                    $g_con = explode('_', $values);
                    $goods_id = $g_con[0];
                    $sku_id = $g_con[1];
                    $sku_arr = explode(',', $sku_ids);
                    $buys_num = $redis->hget($redis_key, $values);
                    $hash_key = $goods_id . '_' . $sku_id;
                    foreach ($sku_arr as $ke => $va) {

                        if ($sku_id == $va) {
                            $spec_ids[] = $sku_id;
                            $spec_count_map[$sku_id] = $buys_num;
                            $ret[$keys]['goods_id'] = $goods_id;
                            $redis->hdel($redis_key, $hash_key);//删除购物车数据
                        }
                    }
                }

            } else {
                $spec_ids = $sku_ids;
            }


            $goodsSku = new GoodsSpecificationSku();
            $goodsList = $goodsSku->getGoodsList($spec_ids);

            $goodsList = toArray($goodsList);
            if (empty($goodsList)) {
                $this->success('请求成功!', ['list' => []]);
            }

            if ($buys_type == 2) {//从购物车里获取

                $goods_ids = assoc_unique($ret, 'goods_id');
                $goods_ids_arr = array_column($goods_ids, 'goods_id');//二维数组转一维数组
            } else {
                $goods_ids_arr = $goodsList[0]['goods_id'];
            }


            // $goodsModel = model('app\common\model\Goods');
            // $shop_ids = $goodsModel->whereIn('id', $goods_ids_arr)->select();//查询商家
            // foreach ($shop_ids as $row) {
            //     $row->visible(['id', 'merchant_id']);
            // }
            // $shop_ids = toArray($shop_ids);
            // $shop_ids = assoc_unique($shop_ids, 'merchant_id');
            $argv = [];
            $all_price = 0;
            $allFreight=0;
            // foreach ($shop_ids as $k => $v) {
                // $argv[$k]['merchant_id'] = $v['merchant_id'];
                $shop_price = 0;
                foreach ($goodsList as $key => &$goods) {

                    if (/*$goods['status']==1||*/$goods['is_del']){
                        $goodsName='商品《'.$goods['goods_name'].'》已下架或删除，请重试';
                        $this->error($goodsName);
                    }
                    $goods['buy_num'] = $buys_type == 1 ? $userBuyNum : $spec_count_map[$goods['id']];
                    if ($goods['stock']<$goods['buy_num']){
                        $goodsName='商品《'.$goods['goods_name'].'》库存不足';

                        $this->error($goodsName);
                    }
                    // if ($goods['merchant_id'] == $v['merchant_id']) {
                        $goods['all_price'] = $goods['current_price'] * $goods['buy_num'];
                        $argv['goods'][] = $goods;
                        $shop_price += $goods['current_price'] * $goods['buy_num'];
                        $all_price += $goods['current_price'] * $goods['buy_num'];
                    // }
                    //运费
                    if($address_type==1){

                        $Freight= $this->allFreight($goods,$address_id,$userBuyNum);
                        if(!is_numeric($Freight)) {
                            return $Freight;
                        }
                    }else{
                        $Freight=0;
                    }
                    $allFreight+=$Freight;

//                    // 计算邮费
//                    $Freight += $this->allFreight($goods,$address_id,$buy_num);
////                    dd($Freight);
//                    $allFreight+=$Freight;
//                    $argv[$k]['Freight'] =$Freight;

                }
                $argv['Freight'] =$allFreight;
                $argv['shop_price'] = $shop_price;
            // }

            $orderModel = new \app\common\model\Order();
            $orderGoodsModel = new \app\common\model\OrderGoods();
            $order_sn = get_order_sn();

            // 启动事务
            Db::startTrans();
            try {
                if ($address_type == 1) {
                    $addressInfo['create_time'] = time();
                    unset($addressInfo['id']);
                    unset($addressInfo['is_default']);
                    unset($addressInfo['delete_time']);
                    $add_id = Db::name('order_address')->insertGetId($addressInfo);
                } else {
                    $add_id = $address_id;

                }
                //单商户的
                $order['order_sn'] = $order_sn;
                $order['user_id'] = $userId;
                $order['order_price'] = $argv['shop_price']+$argv['Freight'];
                $order['freight'] = $argv['Freight'];
                $order['money'] = $argv['shop_price'];
                $order['createtime'] = time();
                $order['address_id'] = $add_id;
                $order['remarks'] = $remarks;
                $thisOrderId = $orderModel->insertGetId($order);
                //插入子订单商品
                foreach ($argv['goods'] as $ket => $val) {
                    $orderGoods['order_id'] = $thisOrderId;
                    $orderGoods['sku_id'] = $val['id'];
                    $orderGoods['goods_id'] = $val['goods_id'];
                    $orderGoods['sku_name'] = $val['name'];
                    $orderGoods['goods_num'] = $val['buy_num'];
                    $orderGoods['goods_price'] = $val['current_price'];
                    $orderGoods['images'] = $val['images'];
                    $orderGoods['goods_name'] = $val['goods_name'];
                    $orderGoodsModel->create($orderGoods);
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error('错误请重试');
            }

            $this->success('请求成功!', ['order_sn' => $order_sn]);
        } else {
            $this->error('请选择商品');
        }
    }


    /**
     * @DESC:
     * @author: renyixu
     * @Time: 2020/11/6   3:35 下午
     * 订单支付
     */
    public function weChatPay(){
        $order_sn = input('order_sn');
        if (!$order_sn) {
            $this->error('没有订单号');
        }
        $userId = $this->auth->id;
        $openid = $this->auth->openid;
        $orderModel = new \app\common\model\Order();
        //$orderInfo = $orderModel->where('order_sn', '=', $order_sn)->where('user_id', '=', $userId)->find();
        $orderInfo = $orderModel->where('order_sn', '=', $order_sn)->find();
        if (empty($orderInfo)) {
            $this->error('当前订单不存在');
        }
        $price = $orderInfo['money'];
        (new Pay)->weChat($order_sn,$price,$openid);

    }
    /**
     * app 支付
     */
    public function AppPay(){
        $order_sn = input('order_sn');
        $mode = input('mode',1);//1微信2支付宝
        if (!$order_sn) {
            $this->error('没有订单号');
        }
//        $userId = $this->auth->id;
//        $openid = $this->auth->openid;
        $orderModel = new \app\common\model\Order();
        //$orderInfo = $orderModel->where('order_sn', '=', $order_sn)->where('user_id', '=', $userId)->find();
        $orderInfo = $orderModel->where('order_sn', '=', $order_sn)->find();
        if (empty($orderInfo)) {
            $this->error('当前订单不存在');
        }
        $price = $orderInfo['order_price'];
        //        //支付订单
        //        //TODO $pay_mode 支付方式1 微信2支付宝 $price 支付钱 $order_sn 订单号 $notify_url 回调地址  $body 支付的标题
        (new Pay)->pay($mode, $price, $order_sn, "http://kuajing123.191292.net/api/pay/courseNotify", '订单支付');
    }

    /**
     * 订单支付
     * */
    public function payOrderWeb(){
        $order_sn = input('order_sn');
        $mode = input('mode',1);//1微信2支付宝
        $orderInfo = MyModel::where('order_sn', $order_sn)->find();

        if ($orderInfo->status != 1) {
            $this->error('当前订单不可执行此操作');
        }
        if ($orderInfo->user_id != $this->auth->id) {
            $this->error('请本人操作');
        }
//        $orderInfo->updatetime = time();
        $orderInfo->mode = $mode;
        $orderInfo->save();

        $price = $orderInfo->money;
        //        //支付订单
        //        //TODO $pay_mode 支付方式1 微信2支付宝 $price 支付钱 $order_sn 订单号 $notify_url 回调地址  $body 支付的标题
        (new Pay)->webpay($mode, $price, $order_sn, "http://kuajing123.191292.net/api/pay/courseNotify", '订单支付');
    }
    /**
     * 小程序订单支付
     * */
    public function payOrdermMniapp(){
        $order_sn = input('order_sn');
        $code = input('code');
        $openID = getOpenid($code);
//        dd($openID);
        if(empty($openID)){
            $this->error('信息获取失败');
        }
//        $mode = input('mode',1);//1微信2支付宝
        $orderInfo = MyModel::where('order_sn', $order_sn)->find();

        if ($orderInfo->status != 1) {
            $this->error('当前订单不可执行此操作');
        }
        if ($orderInfo->user_id != $this->auth->id) {
//            $this->error('请本人操作');
        }

        $price = $orderInfo->order_price;
        //        //支付订单
        //        //TODO $pay_mode 支付方式1 微信2支付宝 $price 支付钱 $order_sn 订单号 $notify_url 回调地址  $body 支付的标题http://fubao.191292.net/brvApBTajs.php/index/login.html
        (new Pay)->payMniapp( $price, $order_sn, "http://kuajing123.191292.net/api/pay/courseNotify", '订单支付',['openid'=>$openID]);
    }
    /**
     * 支付订单
     */
    public function payOrder() {
        $order_sn = input('order_sn');
        if (!$order_sn) {
            $this->error('没有订单号');
        }
        $userId = $this->auth->id;
        $orderModel = new \app\common\model\Order();
        $orderInfo = $orderModel->where('order_sn', '=', $order_sn)->where('user_id', '=', $userId)->find();
        if (empty($orderInfo)) {
            $this->error('当前订单不存在');
        }
        $userInfo = $this->auth->getUserinfo();
        if ($userInfo['score'] < $orderInfo['order_price']) {
            $this->error('积分不足');
        }
        $is_stock = $this->setStock($orderInfo->id);

        // 启动事务
        Db::startTrans();
        try {

            if (!$is_stock) {
                throw new \Exception('库存不足支付失败');
            }
            \app\common\model\User::score($orderInfo['order_price'], $userId, '购物兑换', 2, $order_sn);//扣除积分
            $setdata['status'] = 2;
            $setdata['paytime'] = time();
            $setdata['money'] = $orderInfo['order_price'];
            if ($orderInfo['address_type'] == 2) {
                //获取邀请码  返回url
                $invite_code = myRand();
                $setdata['invite_code'] = $invite_code;
                $my_invite_code = $this->setCode($invite_code);
                $setdata['qrcode'] = $my_invite_code;
                $setdata['paytime'] = time();
                $setdata['status'] = 3;
                $setdata['sendtime'] = time();

            }
            $orderModel->Update($setdata, ['order_sn' => $order_sn]);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('请求成功!', []);

    }

    /**
     * 获取订单列表
     */
    public function getOrderList() {
        $user_id = $this->auth->id;
        $status = input('status/d');
        $goods_name = input('goods_name');
        $where = [];
        if ($status) {
            $where['status'] = $status;
        }else{
            $where['status'] = ['<>',6];
        }
        if($goods_name){

            $where1['goods_name'] = ['like', "%" . $goods_name . "%"];
            $orderGoodsIds = OrderGoods::with('order')
                ->where('user_id', $user_id)
                ->where($where1)
                ->column('order_id');
            $where['id'] = ['in', $orderGoodsIds];
        }

        $orderModel = new \app\common\model\Order();
        $list = $orderModel->with(['orderGoods'])->where($where)->where('user_id', '=', $user_id)->order('createtime desc')
//            ->where('status','<>','6')
            ->paginate();
        $list = toArray($list);
        foreach ($list['data'] as $ke => &$v) {
            $logisticModel = LogisticCode::where('name', '=', $v['logistic_code'])->find();
            $v['OrderRefundStatus']='';
            if($v['status']==6){
                $OrderRefund = OrderRefund::where('order_id', '=', $v['id'])->find();
                if(!empty($OrderRefund)){
                    $v['OrderRefundStatus'] = $OrderRefund['status'];
                }
            }
            $v['logistic_short'] = $logisticModel['logistic_code'];
            foreach ($v['order_goods'] as $kk=>$vv){
                $v['order_goods'][$kk]['thumbnail_image']=$vv['images'];
            }
        }
        $this->success('请求成功!', $list);
    }

    /**
     * 查看订单详情
     */
    public function getOrderInfo() {
        $order_id = input('order_id/d');
        $orderModel = new \app\common\model\Order();
        $info = $orderModel->with(['orderGoods'])->where('id', '=', $order_id)->find();

        foreach ($info['order_goods'] as $k=>$v){

            $v['thumbnail_image']=$v['images'];

        }
//        dd($info);
        $info['logistic_short'] = '';

            $addressInfo = Db::table('sp_order_address')->where('id', '=', $info['address_id'])->find();
            $info['addressInfo'] = $addressInfo;
            $logisticModel = LogisticCode::where('name', '=', $info['logistic_code'])->find();
            $info['logistic_short'] = $logisticModel['logistic_code'];


        $this->success('请求成功!', ['info' => $info]);
    }

    /**
     * 取消订单
     */
    public function cancelOrder() {
        $order_id = input('order_id/d');
        $orderModel = new \app\common\model\Order();
        $info = $orderModel->getById($order_id);
        if ($info->status == '1') {
            $orderModel->where('id', '=', $order_id)->update(['canceltime' => time(), 'status' => 7]);
        } else {
            $this->error('当前订单不可取消');
        }
        $this->success('请求成功!', null);
    }

    /**
     * 确认收货
     */
    public function completeOrder() {
        $order_id = input('order_id/d');
        $orderModel = new \app\common\model\Order();
        $user_id = $this->auth->id;
        $orderInfo = $orderModel->where('id', '=', $order_id)->find();
        if (empty($orderInfo)) {
            $this->error('订单不存在');
        }
            if ($orderInfo->status == '3') {
                Db::startTrans();
                try {
                    $orderModel->where('id', '=', $order_id)->Update(['receipttime' => time(), 'status' => 5]);
                    $goodsModel = new \app\common\model\Goods();
                    //增加销量
                    //获取订单商品
                    $orderGoodsList = toArray(OrderGoods::all(['order_id' => $order_id]));
                    foreach ($orderGoodsList as $k => $v) {
                        $goodsModel::where('id', '=', $v['goods_id'])->setInc('sell_num', $v['goods_num']);
                        //获取当前商品信息 如果实际销量超过失效值则覆盖
                        $goodsInfo = $goodsModel->where('id', '=', $v['goods_id'])->field('id,sold_number,sell_num')->find();
                        if ($goodsInfo['sell_num'] >= $goodsInfo['sold_number']) {
                            $goodsInfo::update(['sold_number' => $goodsInfo['sell_num']], ['id' => $v['goods_id']]);
                        }
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success('请求成功!', null);
            } else {
                $this->error('当前订单不可执行此状态');
            }

    }


    /**
     * 订单评价
     */
    public function orderEvaluation() {

        $userId = $this->auth->id;
        $order_id = $this->request->param('order_id/d');
        $data['goods_id'] = $this->request->param('goods_id');//评论商品
        $data['content'] = $this->request->param('content');//评论内容
        $data['level'] = $this->request->param('level');//星级
        $data['images'] = $this->request->param('images');//图片
        $data['user_id'] = $userId;//用户

        if (empty($order_id)) {
            $this->error('未获取到订单消息', null);
        }
        $orderInfo = MyModel::get(['id' => $order_id]);
        $ordergoods = OrderGoods::get(['order_id'=>$order_id,'goods_id'=> $data['goods_id']]);
        if(!$ordergoods){
            $this->error('商品信息错误', null);
        }
        $data['sku_name'] =$ordergoods['sku_name'];//规格名
        if ($ordergoods->is_comment != 0) {
            $this->error('当前订单不可进行此操作', null);
        }

        if(GoodsComment::create($data)){

            $ordergoods->is_comment=1;
            $ordergoods->save();
            $OrderGoods = OrderGoods::where(['order_id'=>$order_id,'is_comment'=>0])->find();
            if(!$OrderGoods){
                $orderInfo->completetime=time();
                $orderInfo->status=4;
                $orderInfo->save();
            }
            $this->success('评论成功!');
        }


    }
//----------------------------------------------------------------
//| 售后
//----------------------------------------------------------------
    /*
     * 售后
     * */
    public function orderRefund(){
        $user_id = $this->auth->id;
        $data['order_id'] = $this->request->param('order_id');
        $order = MyModel::get($data['order_id']);
        if(empty($order)){
            $this->error('订单有误');
        }

        if($order['status']!=3 && $order['status']!=2 ){
            $this->error('订单状态有误');
        }

        $data['reason']   = $this->request->param('reason');//退款原因

        $data['images']   = $this->request->param('images');//
        $data['reason_desc']     = $this->request->param('reason_desc');//退款原因描述
        $data['types']    = $this->request->param('types',1);//1 退货退款，2退款
//        $data['is_cargo']    = $this->request->param('is_cargo',1);//1未收货 2 已收货
        $data['goods_state']    = $this->request->param('goods_state');//1未收货 2 已收货
        $data['price']   = $order['order_price'];
        $data['status']  = 1;
        $data['user_id'] = $user_id;
        $data['order_status'] = $order['status'];

        if(OrderRefund::create($data)){
            $order->status=6;
            $order->save();
            $this->success('申请成功');
        }
        $this->error('失败');
    }
    /*
     * 售后列表
     * */
    public function  afterSale(){
        $user_id = $this->auth->id;
        $where['a.user_id'] =$user_id;
        $list = OrderRefund::getlist($where);

        $this->success('成功',$list);
    }
    /*
     * 售后 填写快递单号
     * */
    public function  afterSaleLogistic(){
        $user_id = $this->auth->id;
        $id =$this->request->param('id');
        $logistic_num =$this->request->param('logistic_num');
        $logistic =$this->request->param('logistic');
        $where['user_id'] =$user_id;
        $where['id'] =$id;
        $list = OrderRefund::where($where)->find();
//        dd($where);
        if($list['status']!=2){
            $this->error('商家未同意');
        }
        $list->logistic_num=$logistic_num;
        $list->logistic=$logistic;
        $list->save();

        $this->success('成功',$list);
    }

    /*
     * 撤销申请
     * */
    public function afterSaleRepeal(){
        $user_id = $this->auth->id;
        $id =$this->request->param('id');
        $where['user_id'] =$user_id;
        $where['id'] =$id;
        $where['status'] =["<>",4];
        $where['status'] =["<>",-1];
        $OrderRefund = OrderRefund::where($where)->order('id desc')->find();
        if($OrderRefund['status']==4){
            $this->error('已撤销');
        }
        $OrderRefund->status=4;
        $OrderRefund->save();

        $Order = \app\common\model\Order::get($OrderRefund['order_id']);
        if(!empty($Order)){
//            if($Order['logistic_num']){
//                $Order->status=$OrderRefund;
//            }else{
//            }
            $Order->status=$OrderRefund['order_status'];
            $Order->save();
        }
        $this->success('成功');
    }

    /*
      * 售后详情
      * */
    public function  afterSaleInfo(){
        $user_id = $this->auth->id;
        $id =$this->request->param('id');
        $where['a.user_id'] =$user_id;
        $where['a.id'] =$id;
        $list = OrderRefund::getInfo($where);

        $this->success('成功',$list);
    }

    //运费  $goods 商品信息  $address_id地址id $buy_num 购买数量
    public function allFreight($goods,$address_id,$buy_num){
        // 计算邮费
        $allFreight=0;
//        dd($address_id);
        if($goods['is_ship'] == 1 && !empty($address_id)){
            $addressInfo = Address::get($address_id);
            $freight_type = $goods['freight_type']; //0计件 1计重
            if ($freight_type == 0) {
                $type = '2';
            } else {
                $type = '1';
            }
            $logInfo = Db::name('logistics')
                ->where('deletetime', null)
                ->where('id', $goods['freight_id'])
            //    ->where('type', $type)
                ->find();
         //   dd($logInfo);
            if (empty($logInfo)) {
                return $this->error('运费模板不存在');
                // return '运费模板不存在';
            }
            $freightList = Db::name('logistics_fee')
                ->where('deletetime', null)
                ->where('logistics_id', $goods['freight_id'])
                ->select();

            if (empty($freightList)) {
                return $this->error('运费计算错误');

                // return '运费计算错误';
            }
//            dd($freightList);
            $findThis = false;
            foreach ($freightList as $k1 => $v1) {
                if ($v1['city_ids'] == 0) {
                    $first_weight = $v1['first_weight'];//  首重/件
                    $first_weight_price = $v1['first_weight_price'];// 首重/件 价格
                    $next_weight = $v1['next_weight']; // 续重/件
                    $next_weight_price = $v1['next_weight_price'];// 续重/件 价格
                    $findThis = true;
                    break;
                } else {
                    //先进行匹配
                    $cityarr = explode(',', $v1['city_ids']);
                    if (in_array($addressInfo['province_id'], $cityarr)) {
                        $first_weight = $v1['first_weight'];//  首重/件
                        $first_weight_price = $v1['first_weight_price'];// 首重/件 价格
                        $next_weight = $v1['next_weight']; // 续重/件
                        $next_weight_price = $v1['next_weight_price'];// 续重/件 价格
                        if (in_array($addressInfo['city_id'], $cityarr)) {
                            $first_weight = $v1['first_weight'];//  首重/件
                            $first_weight_price = $v1['first_weight_price'];// 首重/件 价格
                            $next_weight = $v1['next_weight']; // 续重/件
                            $next_weight_price = $v1['next_weight_price'];// 续重/件 价格
                        }
                        $findThis = true;
                    }
                }
            }
            if ($findThis) {
                //全国
                if ($freight_type == 0) {
                    //计件
                    $next_num = $buy_num - $first_weight;
                } else {
                    //计重
                    //计算总重量
                    $weights = $buy_num * $goods['weight'];
                    $next_num = $weights - $first_weight;
                }
                if ($next_num <= 0) {
                    $argv['freight'] = $first_weight_price;
                } else {
                    $next_nums = ceil($next_num / $next_weight);
                    $argv['freight'] = $first_weight_price + ($next_nums * $next_weight_price);
                }
            } else {
                return $this->error($goods['goods_name'] . '暂不配送该地区');

                return $goods['goods_name'] . '暂不配送该地区';
            }
//            dd($argv['freight']);
        }else{
            $argv['freight'] = 0;
        }
        $allFreight += $argv['freight'];

        return $allFreight;
    }
//    /**
//     * @Notes:
//     * @Interface refundList
//     * @throws \think\db\exception\DataNotFoundException
//     * @throws \think\db\exception\ModelNotFoundException
//     * @throws \think\exception\DbException
//     * @author: Lw
//     * @Date: 2021/2/3
//     * @Time: 17:46
//     */
//    public function shezhi(){
//        //设置运费
//        $info =  $this->a_1 = $this->auth->id;
//        dd($info);
//        $info['info'] = 1;
//        $info['data'] = getcwd();
//        $this->success('成功',$info);
//    }
    /*
     * 退款原因
     * */
    public function refundList(){
        $where['type']=input('type',1);
        $list =  Refund::where($where)->select();
        $this->success('成功',['list'=>$list]);
    }

    /**
     * 订单支付查询
     * */
    public function orderSn(){
        sleep(1);
        $order_sn = $this->request->param('order_sn');
        $where['order_sn']=$order_sn;
        $order = \app\common\model\Order::where( $where)->find();
        $data = 0;
        if(!empty($order['paytime'])){
            $data = 1;
        }
        $this->success('成功',$data);
    }
}